from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .. models import Users,Goods,Order,OrderInfo
import time,os
from django.contrib.auth.hashers import make_password
from django.core.paginator import Paginator
# Create your views here.
def index(request):
    return render(request,'myadmin/index.html')
def login(request):
    return render(request,'myadmin/login.html')
def dologin(request):
     # 获取用户是否存在
    print(request.session)
    if request.session['verifycode'].lower() != request.POST['vcode'].lower():
        return HttpResponse('<script>alert("验证码错误");location.href="/myadmin/login"</script>')
    
    ob = Users.objects.get(username = request.POST['username'])
    try:
    # 判断是否为管理员
        if ob.status == 'b':
            from django.contrib.auth.hashers import check_password
            res = check_password(request.POST['password'],ob.password)
            if res:
                request.session['AdminLogin']={'uid':ob.id,'username':ob.username,'pic':ob.pic}
                return HttpResponse('<script>alert("登录成功");location.href="/myadmin/"</script>')
            else:
                # 密码错误
                raise
        else:
            raise
    except:
        pass
    return HttpResponse('<script>alert("用户名或密码不正确");location.href="/myadmin/login"</script>')
# 退出登录
def logout(request):

    # 清除session登录信息
    request.session['AdminLogin'] = {}

    return HttpResponse('<script>location.href="/myadmin/login"</script>')

def useradd(request):
    return render(request,'myadmin/user/useradd.html')

def userinsert(request):

    ob = Users()
    ob.username = request.POST['username']
    ob.password = make_password(request.POST['password'], None, 'pbkdf2_sha256')
    ob.phone = request.POST['phone']
    ob.age = request.POST['age']
    ob.sex = request.POST['sex']
    ob.email = request.POST['email']
    ob.status = request.POST['status']
    # print(ob.status)
    ob.address = request.POST['address']
    # 有头像上传work
    if request.FILES.get('pic',None):
        ob.pic = upload(request)
    #提交到数据库
    ob.save()
    return HttpResponse('<script>alert("成功");location.href="/myadmin/userlist"</script>')
    # except:
    #     return HttpResponse('<script>alert("失败");location.href("/myadmin/useradd")</script>')

def userlist(request):
    types = request.GET.get('type',None) 
    # 判断是否有用户名的查询条件
    if types == 'username':
        ob = Users.objects.filter(username__contains=request.GET.get('keywords',''))
    # 是否有性别查询
    elif types == 'sex':
        if request.GET.get('keywords','') == '男':
            ob = Users.objects.filter(sex ='0').order_by('id')
        elif request.GET.get('keywords','') == '女':
            ob = Users.objects.filter(sex = '1').order_by('id') 
        else:
            ob = Users.objects.filter().order_by('id')
    # 是否有状态查询
    elif types == 'status':
        if request.GET.get('keywords','') == '普通会员':
            ob = Users.objects.filter(status = 'a').order_by('id')
        elif request.GET.get('keywords','') == '管理者':
            ob = Users.objects.filter(status = 'b').order_by('id') 
        elif request.GET.get('keywords','') == '已禁用':
            ob = Users.objects.filter(status = 'c').order_by('id')
        else:
            ob = Users.objects.filter().order_by('id')
    else:
        # 按照查询条件进行查询
        ob = Users.objects.filter().order_by('id')
    
    
    # 实例化分页类,一页有两条数据
    paginator = Paginator(ob,2)
     # 浏览器路径？后面参数,获取当前页码
    p = int(request.GET.get('p',1))
     # 获取当前页的所有数据
    userinfo= paginator.page(p)
    print(userinfo)
    context = {'users':userinfo,'p':p}
    return render(request,'myadmin/user/userlist.html',context)



def userdel(request,uid):
    ob = Users.objects.get(id=uid)
    print(ob.pic,type(ob.pic))
    ob.delete()
    # 判断用户头像是否为默认头像
    if ob.pic != "/static/public/pics/1.jpg":
        os.remove('.'+ob.pic)
    return HttpResponse('<script>alert("删除成功");location.href="/myadmin/userlist"</script>') 

def useredit(request,uid):   
    ob = Users.objects.get(id=uid)
    print(ob.status)
    context = {'info':ob}

    return render(request,'myadmin/user/useredit.html',context)
def userupdate(request):   
    try:
        ob = Users.objects.get(id=request.POST['uid'])
        ob.username = request.POST['username']
        if request.POST['password']:
            # 判断是否修改密码
            ob.password = make_password(request.POST['password'], None, 'pbkdf2_sha256')
        ob.phone = request.POST['phone']
        ob.age = request.POST['age']
        ob.sex = request.POST['sex']
        ob.email = request.POST['email']
        ob.status = request.POST['status']
        ob.address = request.POST['address']
        # 有头像上传work
        if request.FILES.get('pic',None):
            if ob.pic != '/static/public/pics/1.jpg':
                os.remove('.'+ob.pic) 
            ob.pic = upload(request)
        #提交到数据库
        ob.save()
        return HttpResponse('<script>alert("用户修改成功");location.href="/myadmin/userlist"</script>')
    except:
        return HttpResponse('<script>alert("修改失败");location.href="/myadmin/useredit/'+str(ob.id)+'"</script>')
    
def upload(request):

    #执行图片的上传
    myfile = request.FILES.get("pic",None)
    print(myfile)
    filename = str(time.time())+"."+myfile.name.split('.').pop()
    destination = open("./static/public/pics/"+filename,"wb+")
    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)  
    destination.close()
    return '/static/public/pics/'+filename

def verifycode(request):
    #引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    #引入随机函数模块
    import random
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 40
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    #定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    # str1 = '123456789'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象
    font = ImageFont.truetype('NotoSansCJK-Light.ttc', 23)
    # font = ImageFont.load_default().font
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    #内存文件操作
    import io
    buf = io.BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')

def order(request):
    ob = OrderInfo.objects.all()
    # print(ob)
    # for x in ob:
    #     x.sub=OrderInfo.objects.filter(orderid_id=x.id)
    #     for xx in x.sub:
    #         xx.good=Goods.objects.filter(id=xx.gid_id)
    #         for v in xx.good:
    #             print(v.title)
    #     x.user=Users.objects.get(id=x.uid.id)
    
    paginator = Paginator(ob,5)
     # 浏览器路径？后面参数,获取当前页码
    p = int(request.GET.get('p',1))
     # 获取当前页的所有数据
    userinfo= paginator.page(p)
    print(userinfo)
    context={'info':userinfo}
    
    
    return render(request,'myadmin/order.html',context)
def orderxq(request,uid):

        
    ob = OrderInfo.objects.get(id=uid)

    context={'orderinfo':ob}



    return render(request,'myadmin/orderxq.html',context)



def orderedit(request,uid):

    om = Order.objects.get(id = uid)
    context ={'oddd':om}

    return render(request,'myadmin/orderedit.html',context)

def orderupdate(request):

    ob = Order.objects.get(id=request.POST['oid'])

    ob.addname = request.POST['addname']
    ob.addphone = request.POST['addphone']
    ob.addcode = request.POST['addcode']
    ob.address = request.POST['address']

    ob.save()


    return HttpResponse('<script>alert("修改成功");location.href="/myadmin/order"</script>')